// 云函数入口文件
const {
  promises
} = require('fs');
const cloud = require('wx-server-sdk')
cloud.init()

// 云函数入口函数
exports.main = async (event, context) => {
  let number = event.number;
  let mobile = event.mobile;
  var CryptoJS = require("crypto-js");
  var request = require('request');
  var querystring = require('querystring');
  // 云市场分配的密钥Id
  var secretId = process.env.secretId;
  // 云市场分配的密钥Key
  var secretKey = process.env.secretKey;
  var source = "market";
  // 签名
  var datetime = (new Date()).toGMTString();
  var signStr = "x-date: " + datetime + "\n" + "x-source: " + source;
  var sign = CryptoJS.enc.Base64.stringify(CryptoJS.HmacSHA1(signStr, secretKey))
  console.log('okokokok')
  var auth = 'hmac id="' + secretId + '", algorithm="hmac-sha1", headers="x-date x-source", signature="' + sign + '"';
  // 请求方法
  var method = "POST";
  // 请求头
  var headers = {
    "X-Source": source,
    "X-Date": datetime,
    "Authorization": auth,
  }
  // 查询参数
  var queryParams = {}
  // body参数（POST方法下）
  var bodyParams = {
    "expressCode": "auto",
    "mobile": mobile,
    "number": number
  }
  // url参数拼接
  var url = "https://service-ootu039r-1305308687.sh.apigw.tencentcs.com/release/express/query/v1";
  if (Object.keys(queryParams).length > 0) {
    url += '?' + querystring.stringify(queryParams);
  }

  var options = {
    url: url,
    timeout: 5000,
    method: method,
    headers: headers
  }
  if (['POST', 'PUT', 'PATCH'].indexOf(method) != -1) {
    options['body'] = querystring.stringify(bodyParams);
    options['headers']['Content-Type'] = "application/x-www-form-urlencoded";
  }
  let express_info = new Promise((resolve, reject) => {
    request(options, function (error, response, body) {
      console.log(error)
      if (error !== null) {
        console.log('error:', error);
        reject(body)
      }
      console.log(body);
      resolve(body)
    });
  })
  return express_info;
}